let events = [];
let counts = [];
let barChart = null;
let pieChart = null;
let darkMode = false;

function generateButtons() {
    const input = prompt('请输入事件名称（用逗号分隔）:', '事件1,事件2,事件3');
    const eventNames = input.split(/,|，/); // 支持西文逗号和中文逗号
    events = eventNames;
    counts = Array(eventNames.length).fill(0);
    const buttonContainer = document.getElementById('buttonContainer');
    buttonContainer.innerHTML = '';
    eventNames.forEach((event, index) => {
        const button = document.createElement('button');
        button.textContent = event;
        button.onclick = () => countVote(index);
        buttonContainer.appendChild(button);
    });
    updateTable();
    updateCharts();
}

function countVote(index) {
    counts[index]++;
    updateTable();
}

function updateTable() {
    const tbody = document.getElementById('resultTable').querySelector('tbody');
    tbody.innerHTML = '';
    
    events.forEach((event, index) => {
        const row = document.createElement('tr');
        const eventCell = document.createElement('td');
        eventCell.textContent = event;
        const countCell = document.createElement('td');
        countCell.textContent = counts[index];
        row.appendChild(eventCell);
        row.appendChild(countCell);
        tbody.appendChild(row);
    });

    updateCharts();
}

function updateCharts() {
    const ctxBar = document.getElementById('barChart').getContext('2d');
    const ctxPie = document.getElementById('pieChart').getContext('2d');
    
    const colors = counts.map((_, index) => `hsl(${index * 60}, 70%, 60%)`);

    if (!barChart) {
        barChart = new Chart(ctxBar, {
            type: 'bar',
            data: {
                labels: events,
                datasets: [{
                    label: '票数',
                    data: counts,
                    backgroundColor: colors
                }]
            },
            options: {
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });
    } else {
        barChart.data.labels = events;
        barChart.data.datasets[0].data = counts;
        barChart.update();
    }

    if (!pieChart) {
        pieChart = new Chart(ctxPie, {
            type: 'pie',
            data: {
                labels: events,
                datasets: [{
                    data: counts,
                    backgroundColor: colors
                }]
            }
        });
    } else {
        pieChart.data.labels = events;
        pieChart.data.datasets[0].data = counts;
        pieChart.update();
    }
}

function confirmReset() {
    if (confirm("确定要清零吗？")) {
        resetVotes();
    }
}

function resetVotes() {
    counts = [];
    events = [];
    document.getElementById('buttonContainer').innerHTML = '';
    document.getElementById('resultTable').querySelector('tbody').innerHTML = '';
    if (barChart) barChart.destroy();
    if (pieChart) pieChart.destroy();
    barChart = null;
    pieChart = null;
}

function exportToJPG() {
    html2canvas(document.body).then(canvas => {
        const link = document.createElement('a');
        link.download = 'data.jpg';
        link.href = canvas.toDataURL('image/jpeg');
        link.click();
    });
}

function adjustFontSize(size) {
    document.body.style.fontSize = size + 'px';
    const buttons = document.querySelectorAll('button');
    buttons.forEach(button => button.style.fontSize = size + 'px');
    const tableCells = document.querySelectorAll('th, td');
    tableCells.forEach(cell => cell.style.fontSize = size + 'px');
}

function showInstructions() {
    alert(`使用说明：
· 点击“设定”来设置计票名称
· 点击“清零”来清除软件数据
· 拖动右上角滑块来调整页面字体大小
· 不要修改页面源代码，可能会导致软件崩溃

©2024 Zijun Bai. All Rights Reserved.`);
}

function showVersionInfo() {
    alert(`版本说明：
版本1.2 20240610 正式版
©2024 Zijun Bai. All Rights Reserved.`);
}

function toggleDarkMode() {
    darkMode = !darkMode;
    document.body.classList.toggle('dark-mode', darkMode);
    const allElements = document.querySelectorAll('*');
    allElements.forEach(element => {
        element.style.transition = 'background-color 0.3s, color 0.3s';
    });
}

function sortVotes() {
    const sortOption = confirmSortOrder();
    if (sortOption === '小-大') {
        sortByAscending();
    } else if (sortOption === '大-小') {
        sortByDescending();
    }
}

function confirmSortOrder() {
    const option = prompt('按照小-大还是大-小排列？\n1. 小-大\n2. 大-小\n3. 取消');
    if (option === '1') return '小-大';
    if (option === '2') return '大-小';
    return '取消';
}

function sortByAscending() {
    const sortedIndices = [...Array(events.length).keys()].sort((a, b) => counts[a] - counts[b]);
    events = sortedIndices.map(index => events[index]);
    counts = sortedIndices.map(index => counts[index]);
    updateTable();
}

function sortByDescending() {
    const sortedIndices = [...Array(events.length).keys()].sort((a, b) => counts[b] - counts[a]);
    events = sortedIndices.map(index => events[index]);
    counts = sortedIndices.map(index => counts[index]);
    updateTable();
}

adjustFontSize(document.getElementById('fontSizeSlider').value);